package models

import (
	"fmt"
	"strings"
)

/////////////////////角色操作///////////////////////
//查询角色
func QueryRoleAll() [] Role {
	role_list := [] Role{}
	db.Find(&role_list)
	return role_list
}


func QueryRolePage(page int) [] Role {
	role_list := [] Role{}
	db.Limit(12).Offset(12*(page-1)).Find(&role_list)
	return role_list
}


//添加角色
func AddRole(role Role)  {
	db.Create(&role)
}

//通过ID查询角色
func QueryRoleOne(id int) Role {
	role := Role{}
	db.First(&role,id)
	return role
}

//更新角色
func UpdateRole(id int,obj Role) {
	role := Role{}
	db.First(&role,id).Update(&obj)
}


//更新角色
func UpdateRolePerms(id int,obj Role) {
	role := Role{}
	if obj.Perms !=nil {
		db.First(&role,id).Association("Perms").Clear()
	}
	db.First(&role,id).Update(&obj)
}

//更新角色
func UpdateRolePfm(id int,obj Role) {
	fmt.Println(obj)
	role := Role{}
	if obj.PlatForm !=nil {
		db.First(&role,id).Association("PlatForm").Clear()
	}
	db.First(&role,id).Update(&obj)
}


/*/更新角色
func UpdateRoleAsset(id int,obj Role) {
	role := Role{}
	if obj.Asset !=nil {
		db.First(&role,id).Association("Asset").Clear()
	}
	db.First(&role,id).Update(&obj)
}
*/

//删除角色
func DeleteRole(id int) {
	role := Role{}
	db.First(&role,id).Delete(&role)
}

// 搜索角色
func QueryRoleSearch(key string) []Role {
	role := [] Role{}
	db.Where("role_name LIKE ?", "%"+key+"%").Or("role_msg LIKE ?", "%"+key+"%").Find(&role)
	return role
}

func GetRolePerms(id int) [] int{
	role := Role{}
	db.First(&role,id)
	var menu_list []Menu
	var perm_id_list []int
	db.Model(&role).Related(&menu_list, "Perms")
	for i,_:= range menu_list{
		m_id := int(menu_list[i].ID)
		perm_id_list = append(perm_id_list, m_id)
	}
	return perm_id_list
}


func GetRolePfm(id int) [] int{
	//获取平台
	role := Role{}
	db.First(&role,id)
	var Platfm_list []ItemPlatfm
	var pfm_id_list []int
	db.Model(&role).Related(&Platfm_list, "PlatForm")
	for _,v:= range Platfm_list{
		pfm_id_list = append(pfm_id_list,v.ID)
	}
	return pfm_id_list
}




func GetUserPerms(roles []Role) []int{
	var perm_id_list []int
	for i,_ := range roles{
		id :=  roles[i].ID
		role := Role{}
		db.First(&role,id)
		var menu_list []Menu
		db.Model(&role).Related(&menu_list, "Perms")
		for i,_:= range menu_list{
			m_id := int(menu_list[i].ID)
			perm_id_list = append(perm_id_list, m_id)
		}
	}
	//perm_id_lists := SortList(perm_id_list)
	return perm_id_list
}

func  GetUserMenus(ids []int) []MenuLevel {
	menu_level := MenuLevel{}
	menu_level_list := [] MenuLevel{}
	menu := [] Menu{}
	chil_menu := [] Menu{}
	db.Order("menu_weight desc").Where("p_menu = ?", 0).Where("id in (?)",ids).Find(&menu)
	for i,_ := range menu{
		id := menu[i].ID
		db.Order("menu_weight desc").Where("p_menu = ?", id).Where("id in (?)",ids).Find(&chil_menu)
		menu_level.Menu = menu[i]
		menu_level.CMenus = chil_menu
		menu_level_list = append(menu_level_list, menu_level)
	}
	return menu_level_list
}


/////////////////////用户操作///////////////////////

//查询角色
func QueryUserAll(cur_user string,is_super bool) [] User {
	user_list := [] User{}
	if is_super{
		db.Find(&user_list)
	}else{
		db.Where("user_name = ?",cur_user).Find(&user_list)
	}

	for i,_ := range user_list{
		role_list := GetRoleInfo(&user_list[i])
		user_list[i].RoleNames = role_list
	}
	return user_list
}

func GetRoleInfo(user *User) string{
	var rolename_list string
	var role_list []Role
	db.Model(&user).Related(&role_list, "Roles")
	rolename_list = "["
	for i,_:=range role_list{
		rolename_list = rolename_list + role_list[i].RoleName+","
	}
	//去掉尾部","
	rolename_list = strings.TrimRight(rolename_list, ",")
	rolename_list = rolename_list +"]"
	return rolename_list
}

//添加角色
func AddUser(User User)  {
	db.Create(&User)
}

//通过ID查询角色
func QueryUserOne(id int) User {
	user := User{}
	db.First(&user,id)
	var role_list []Role
	db.Model(&user).Related(&role_list, "Roles")
	user.Roles = role_list
	return user
}

//通过username查询角色
func QueryUserByName(username string) User {
	user := User{}
	db.Where("user_name = ?", username).First(&user)
	var role_list []Role
	db.Model(&user).Related(&role_list, "Roles")
	user.Roles = role_list
	return user
}

//更新
func UpdateUser(id int,obj User) {
	user := User{}
	//Clear - 删除源和当前关联之间的关系，不会删除这些关联
	db.First(&user,id).Association("Roles").Clear()
	db.First(&user,id).Update(&obj)
}


//修改密码
func UpdateUserPwd(id int,obj User) {
	user := User{}
	db.First(&user,id).Update(&obj)
}

//删除角色
func DeleteUser(id int) {
	user := User{}
	//Clear - 删除源和当前关联之间的关系，不会删除这些关联
	db.First(&user,id).Association("Roles").Clear()
	db.First(&user,id).Delete(&user)
}

// 搜索角色
func QueryUserSearch(key,cur_user string,is_super bool) []User {
	user := [] User{}
	if is_super{
		db.Where("user_name LIKE ?", "%"+key+"%").Or("nick_name LIKE ?", "%"+key+"%").Or("mobile LIKE ?", "%"+key+"%").Find(&user)
	}else{
		db.Where("user_name LIKE ? and user_name = ?", "%"+key+"%",cur_user).Or("nick_name LIKE ? and user_name = ?", "%"+key+"%",cur_user).
			Or("mobile LIKE ? and user_name = ?", "%"+key+"%",cur_user).Find(&user)
	}
	return user
}


func GetUserByNameAndPwd(username,passwd string) (User,error){
	user := User{}
	err := db.Where("user_name = ?", username).Where("user_pwd = ?",passwd).First(&user).Error
	var role_list []Role
	db.Model(&user).Related(&role_list, "Roles")
	user.Roles = role_list
	return user,err
}

/////////////////////菜单操作///////////////////////

func QueryMenuAll() [] MenuLevelAll  {
	menu_level_list := [] MenuLevelAll{}

	chil_menu := [] Menu{}
	chil_2_menu := [] Menu{}

	menu_level_all := MenuLevelAll{}
	menu := [] Menu{}

	db.Order("menu_weight desc").Where("p_menu = ?", 0).Find(&menu)
	for i,_ := range menu{
		id := menu[i].ID
		menu_level := MenuLevel{}
		chil_c_menu_list := [] MenuLevel{}
		db.Where("p_menu = ?", id).Find(&chil_menu)
		for j,_ := range chil_menu{
			c_id := chil_menu[j].ID
			db.Where("p_menu = ?", c_id).Find(&chil_2_menu)
			menu_level.Menu = chil_menu[j]
			menu_level.CMenus = chil_2_menu
			chil_c_menu_list = append(chil_c_menu_list, menu_level)
		}
		menu_level_all.Menu = menu[i]
		menu_level_all.MenuLevel = chil_c_menu_list
		menu_level_list = append(menu_level_list, menu_level_all)
	}
	return menu_level_list
}


func QueryMenuLevelOne() [] MenuLevel {
	menu_level := MenuLevel{}
	menu_level_list := [] MenuLevel{}
	menu := [] Menu{}
	chil_menu := [] Menu{}
	db.Where("p_menu = ?", 0).Find(&menu)
	for i,_ := range menu{
		id := menu[i].ID
		db.Where("p_menu = ?", id).Find(&chil_menu)
		menu_level.Menu = menu[i]
		menu_level.CMenus = chil_menu
		menu_level_list = append(menu_level_list, menu_level)
	}
	return menu_level_list
}

//添加
func AddMenu(menu Menu)  {
	db.Create(&menu)
}

//通过ID查询
func GetMenuId(id int) Menu {
	menu := Menu{}
	db.First(&menu,id)
	return menu
}

//更新角色
func UpdateMenu(id int,obj Menu) {
	menu := Menu{}
	db.First(&menu,id).Update(&obj)
}

//删除
func DeleteMenu(id int) {
	menu := Menu{}
	db.First(&menu,id).Delete(&menu)
}


// 搜索
func QueryMenuSearch(key string) [] MenuLevelAll {
	memu_level_0 := [] Menu{}
	memu_level_1 := [] Menu{}
	memu_level_2 := [] Menu{}
	var menu_1_lists [] int
	var menu_0_lists [] int

	menu_level_list := [] MenuLevelAll{}

	menu_level_all := MenuLevelAll{}

	//查询关键字功能菜单
	db.Where("is_menu = ?",0).Where("menu_title LIKE ?", "%"+key+"%").Or("menu_url LIKE ?", "%"+key+"%").Find(&memu_level_2)

	//获取二级菜单ID
	for i,_ := range memu_level_2{
		menu_1_lists = append(menu_1_lists, memu_level_2[i].PMenu)
	}
	//去重
	menu_1_list := SortList(menu_1_lists)

	//获取二级菜单
	db.Where("id in (?)",menu_1_list).First(&memu_level_1)

	//获取一级菜单ID
	for i,_ := range memu_level_1{
		menu_0_lists = append(menu_0_lists, memu_level_1[i].PMenu)
	}
	//去重
	menu_0_list := SortList(menu_0_lists)

	//获取本次查询所展示的一级菜单
	db.Where("id in (?)",menu_0_list).Find(&memu_level_0)
	for  i,_ := range memu_level_0{
		id := memu_level_0[i].ID
		menu_level := MenuLevel{}
		child_c_menu_list := [] MenuLevel{}
		//获取本次查询的二级菜单
		db.Where("p_menu = ?", id).Where("id in (?)",menu_1_list).Find(&memu_level_1)
		for j,_ := range memu_level_1{
			c_id := memu_level_1[j].ID
			//获取本次查询的功能菜单
			db.Where("p_menu = ?", c_id).Where("menu_title LIKE ?", "%"+key+"%").Or("menu_url LIKE ?", "%"+key+"%").Find(&memu_level_2)
			menu_level.Menu = memu_level_1[j]
			menu_level.CMenus = memu_level_2
			child_c_menu_list = append(child_c_menu_list, menu_level)
		}
		menu_level_all.Menu = memu_level_0[i]
		menu_level_all.MenuLevel = child_c_menu_list
		menu_level_list = append(menu_level_list, menu_level_all)
	}

	return menu_level_list
}

func GetPermsUrl(url string) Menu {
	urls := strings.Split(url, "/")
	memu := Menu{}
	if len(urls) >=4 {
		new_url := strings.Join(urls[0:3], "/")

		db.Where("menu_url Like ?","%"+new_url+"%").First(&memu)
	}else{
		db.Where("menu_url Like ?","%"+url+"%").First(&memu)
	}

	return memu
}


func IsExitItem(val int,array []int)  bool {
	for _,v := range array{
		if v == val{
			return true
		}
	}
	return false
}

//int 类型切片 去重
func SortList(arr []int) (newArr [] int) {
	newArr = make([]int, 0)
	for i:=0;i < len(arr);i++{
		repeat := false
		for  j:=i+1;j<len(arr);j++{
			if arr[i] == arr[j] {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return newArr
}

/////////////////////字典操作///////////////////////

//查询
func QueryDictAll() [] Dict {
	dict_list := [] Dict{}
	db.Find(&dict_list)
	return dict_list
}

//查询
func QueryDictPage(page int) [] Dict {
	dict_list := [] Dict{}
	db.Limit(12).Offset(12*(page-1)).Find(&dict_list)
	return dict_list
}


//添加
func AddDict(obj Dict)  {
	db.Create(&obj)
}

//通过ID查询
func QueryDictOne(id int) Dict {
	dict := Dict{}
	db.First(&dict,id)
	return dict
}

//更新角色
func UpdateDict(id int,obj Dict) {
	dict := Dict{}
	db.First(&dict,id).Update(&obj)
}

//删除
func DeleteDict(id int) {
	dict := Dict{}
	db.First(&dict,id).Delete(&dict)
}


// 搜索
func QueryDictSearch(key string) []Dict {
	dict := [] Dict{}
	db.Where("dict_key LIKE ?", "%"+key+"%").Or("dict_val LIKE ?", "%"+key+"%").Find(&dict)
	return dict
}


//通过key查询
func QueryDictKey(key string) (Dict,error) {
	dict := Dict{}
	err :=db.Where("dict_key = ?",key).First(&dict).Error
	return dict,err
}





